package com.iut.utils;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;

import android.hardware.Camera;
import android.net.Uri;
import android.os.Environment;
import android.util.Log;

public class FileHelper 
{
	public static String saveFile(byte[] data) 
	{
		File pictureFile = getOutputMediaFile();
		
        if (pictureFile == null)
        {
            Log.d("PARCEL_TAG", "Error creating media file, check storage permissions");
            return null;
        }

        try {
            FileOutputStream fos = new FileOutputStream(pictureFile);
            fos.write(data);
            fos.close();
            
            Uri pictureUri = getOutputMediaFileUri(pictureFile);
            
            return pictureUri.getPath();
        } 
        catch (FileNotFoundException e) {
            Log.d("PARCEL_TAG", "File not found: " + e.getMessage());
        }
        catch (IOException e) {
            Log.d("PARCEL_TAG", "Error accessing file: " + e.getMessage());
        }
		return null;
	}
	
	/** Create a file Uri from a file */
	private static Uri getOutputMediaFileUri(File pictureFile){
	      return Uri.fromFile(pictureFile);
	}

	/** Create a File for saving an image or video */
	private static File getOutputMediaFile(){
	    // To be safe, you should check that the SDCard is mounted
	    // using Environment.getExternalStorageState() before doing this.

	    File mediaStorageDir = new File(Environment
	    		.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES), "ParcelAppPictures");
	    // This location works best if you want the created images to be shared
	    // between applications and persist after your app has been uninstalled.

	    // Create the storage directory if it does not exist
	    if (! mediaStorageDir.exists()){
	        if (! mediaStorageDir.mkdirs()){
	            Log.d("PARCEL_TAG", "failed to create directory");
	            return null;
	        }
	    }

	    String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss",Locale.US).format(new Date());
	    
	    File mediaFile;
	    mediaFile = new File(mediaStorageDir.getPath() + File.separator + "IMG_"+ timeStamp + ".jpg");

	    return mediaFile;
	}
}
